﻿using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace democlientwebsocket
{
    class Program
    {
        static async Task Main(string[] args)
        {

            var client = new Client();

            while (true)
            {
               await Task.Delay(1000);

                var  msg = new Random(Guid.NewGuid().GetHashCode()).Next(1, 10000);
                await client.SendMessage($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} {msg} ");
            }

            Console.ReadLine();
        }
    }


    public class Client
    {

        private ClientWebSocket _clientWebSocket;
        public   Client()
        {
            Task.Run(async () => await Connect());
        }

        public async Task SendMessage(string message)
        {
            if (_clientWebSocket.State == WebSocketState.Open)
            {
                await   _clientWebSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(message)), WebSocketMessageType.Text,
                    true, CancellationToken.None);
            }
        
        }

        public async Task Connect()
        {
            _clientWebSocket = new ClientWebSocket();
            await _clientWebSocket.ConnectAsync(new Uri("ws://localhost:5000/ws"), CancellationToken.None);
        }
    }
}